// stores/websocket.ts
import { defineStore, storeToRefs } from 'pinia';
import { ref, onUnmounted } from 'vue';

// 定义WebSocket连接状态类型
export type WSStatus = 'INIT' | 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';

// 定义消息格式接口
export interface WSMessage {
  type: string;
  payload: any;
  timestamp?: number;
}

// WebSocket配置选项
interface WSOptions {
  url: string; // WebSocket服务地址(wss://或ws://)
  reconnectDelay?: number; // 重连延迟(ms)，默认3000
  maxReconnectCount?: number; // 最大重连次数，默认无限
  pingInterval?: number; // 心跳检测间隔(ms)，默认30000
  pingMessage?: WSMessage; // 心跳消息内容
}

export const useWebSocketStore = defineStore('websocket', () => {
  // 状态
  const ws = ref<WebSocket | null>(null);
  const status = ref<WSStatus>('INIT');
  const lastError = ref<Event | null>(null);
  const receivedMessages = ref<WSMessage[]>([]);
  const reconnectCount = ref(0);
  const isManualClose = ref(false);
  
  // 配置
  const options = ref<Required<WSOptions>>({
    url: '',
    reconnectDelay: 3000,
    maxReconnectCount: Infinity,
    pingInterval: 30000,
    pingMessage: { type: 'ping', payload: '' }
  });
  
  // 定时器
  let reconnectTimer: NodeJS.Timeout | null = null;
  let pingTimer: NodeJS.Timeout | null = null;

  // 初始化配置
  const init = (wsOptions: WSOptions) => {
    options.value = { ...options.value, ...wsOptions };
  };

  // 连接WebSocket
  const connect = () => {
    if (status.value !== 'INIT' && status.value !== 'DISCONNECTED') {
      console.warn('WebSocket已处于连接状态或正在连接中');
      return;
    }

    isManualClose.value = false;
    status.value = 'CONNECTING';
    
    if (!options.value.url) {
      console.error('WebSocket URL未配置，请先调用init方法');
      status.value = 'DISCONNECTED';
      return;
    }

    ws.value = new WebSocket(options.value.url);

    // 连接成功回调
    ws.value.onopen = () => {
      console.log('WebSocket连接成功');
      status.value = 'CONNECTED';
      reconnectCount.value = 0; // 重置重连计数
      startPing(); // 启动心跳检测
    };

    // 接收消息回调
    ws.value.onmessage = (event) => {
      try {
        const message: WSMessage = {
          ...JSON.parse(event.data),
          timestamp: Date.now()
        };
        receivedMessages.value.push(message);
        // 只保留最近100条消息
        if (receivedMessages.value.length > 100) {
          receivedMessages.value.shift();
        }
      } catch (error) {
        console.error('WebSocket消息解析失败:', error);
        receivedMessages.value.push({
          type: 'RAW',
          payload: event.data,
          timestamp: Date.now()
        });
      }
    };

    // 连接关闭回调
    ws.value.onclose = (event) => {
      console.log(`WebSocket关闭: 代码=${event.code}, 原因=${event.reason}`);
      status.value = 'DISCONNECTED';
      stopPing(); // 停止心跳检测

      // 需要自动重连的情况
      if (!isManualClose.value && reconnectCount.value < options.value.maxReconnectCount) {
        reconnect();
      }
    };

    // 错误回调
    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error);
      lastError.value = error;
    };
  };

  // 手动断开连接
  const disconnect = (code: number = 1000, reason: string = '正常关闭') => {
    isManualClose.value = true;
    stopReconnect();
    stopPing();
    
    if (ws.value) {
      ws.value.close(code, reason);
      ws.value = null;
    }
    status.value = 'DISCONNECTED';
  };

  // 发送消息
  const send = (message: WSMessage): boolean => {
    if (status.value !== 'CONNECTED' || !ws.value) {
      console.error('WebSocket未连接，无法发送消息');
      return false;
    }

    try {
      ws.value.send(JSON.stringify(message));
      return true;
    } catch (error) {
      console.error('WebSocket消息发送失败:', error);
      return false;
    }
  };

  // 重连机制
  const reconnect = () => {
    stopReconnect();
    reconnectCount.value++;
    
    if (reconnectCount.value > options.value.maxReconnectCount) {
      console.error(`已达到最大重连次数(${options.value.maxReconnectCount})，停止重连`);
      return;
    }

    console.log(`准备第${reconnectCount.value}次重连...`);
    reconnectTimer = setTimeout(() => {
      connect();
    }, options.value.reconnectDelay);
  };

  // 启动心跳检测
  const startPing = () => {
    stopPing();
    pingTimer = setInterval(() => {
      if (status.value === 'CONNECTED') {
        send(options.value.pingMessage!);
      }
    }, options.value.pingInterval);
  };

  // 停止心跳检测
  const stopPing = () => {
    if (pingTimer) {
      clearInterval(pingTimer);
      pingTimer = null;
    }
  };

  // 停止重连计时器
  const stopReconnect = () => {
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
  };

  // 清理消息
  const clearMessages = () => {
    receivedMessages.value = [];
  };

  // 组件卸载时清理
  onUnmounted(() => {
    disconnect();
    stopReconnect();
    stopPing();
  });

  return {
    // 状态
    status,
    lastError,
    receivedMessages,
    reconnectCount,
    
    // 方法
    init,
    connect,
    disconnect,
    send,
    clearMessages
  };
});

// 提供一个在组件中使用的 composable
export function useWebSocket() {
  const wsStore = useWebSocketStore();
  return {
    ...wsStore,
    ...storeToRefs(wsStore)
  };
}
// import { defineStore } from 'pinia'
// import {sendSock, createWebSocket, closeSock} from '../utils/websocket'

// export const websocketStore = defineStore('webSock', {
//     state: () => ({
//         webSocketList: {
//             bizType: null,
//             content: '',
//             name: '',
//             types: null,
//             id: '',
//             remindLevel: 0,
//             senderId: null,
//             type: 1,
//             userId: null
//         }
//     }),
//     actions: {
//         WEBSOCKET_LIST(data:any) {
//            console.log('WEBSOCKET_LIST',data)
//            this.webSocketList = data
//         },
//         // 创建websocket
//         init() {
//             console.log('websocket init')
//             createWebSocket(this.handleData)
//         },
//         // 获取消息websocket
//         handleData (res:any){
//             console.log('websocket handleData',res)
//             this.webSocketList.content = ''
//             this.webSocketList.name = ''
//             this.webSocketList.userId = null
//             this.webSocketList.types = null
//             let data = Object.assign(this.webSocketList,res)
//             this.WEBSOCKET_LIST(data)
//         },
//         // 发送消息websocket
//         sendMsg(data: any) {
//             sendSock(data)
//         },
//     }
// })
// export default websocketStore
